import { computed, ref } from 'vue'
import { RouteRecordRaw } from 'vue-router'

import { defineStore } from 'pinia'

import router, { addRoutes, generateRoutes, goChildPath, resetRouter } from '@/router'

import SignApi, { signInDataType } from '@/api/sign'
import { passwordSecret } from '@/api/uses'

import {
  getToken,
  getUserinfo,
  removeAll,
  removeUserinfo,
  setMenu,
  setToken,
  setUserinfo,
} from '@/utils/auth'
import { tryCatchFn } from '@/utils/tryCatch'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken())
  const account = ref(getUserinfo()?.account || '')
  const userInfo = ref(getUserinfo())
  const asyncRoutes = ref<RouteRecordRaw[]>([])

  const uid = computed(() => userInfo.value?.uid)
  const oid = computed(() => userInfo.value?.oid)

  const setAsyncRoutes = (routes: RouteRecordRaw[]) => {
    asyncRoutes.value = routes
  }

  const signIn = async (data: signInDataType) => {
    await tryCatchFn(async () => {
      const password = await passwordSecret(data.password)
      const ret = await SignApi.signIn({ ...data, password })
      const formatRet = JSON.parse(ret)
      console.log('r', ret, formatRet.code, formatRet.data)
      if (formatRet?.data) {
        console.log('a1', formatRet.data)
        getUserInfo(data.account)
        token.value = formatRet.data
        setToken(token.value)
      }
    })
  }

  const getUserInfo = async (account: string) => {
    console.log('a', account)
    const ret = await SignApi.getUserInfo({ account })
    console.log('userInfo', ret)

    userInfo.value = ret
    setUserinfo(userInfo.value)

    const tt = setRoutes(ret.menus)

    router.replace(goChildPath(tt))
  }

  const setRoutes = (routes: any[]) => {
    resetRouter()
    const formatRoutes = generateRoutes(routes)

    setAsyncRoutes(formatRoutes)

    setMenu(routes)

    console.log('r', routes, formatRoutes)

    addRoutes(formatRoutes)

    return formatRoutes
  }

  const signOut = async () => {
    await tryCatchFn(async () => {
      await SignApi.signOut({ account: account.value })

      resetRouter()
      resetData()
      removeAll()

      location.reload()
      // router.replace('/login')
    })
  }

  const updateUserInfo = (params: any) => {
    removeUserinfo()
    userInfo.value = params
    setUserinfo(params)
  }

  const resetData = () => {
    token.value = ''
    userInfo.value = {}
  }

  return {
    token,
    account,
    userInfo,
    asyncRoutes,
    uid,
    oid,
    setAsyncRoutes,
    setRoutes,
    signIn,
    signOut,
    updateUserInfo,
    getUserInfo,
  }
})
